In the Java programming language, the constant interface pattern describes the use of an interface solely to define constants, and having classes implement that interface in order to achieve convenient syntactic access to those constants. However, since constants are very often merely an implementation detail, and the interfaces implemented by a class are part of its exported API, this practice amounts to putting implementations details into the API, which is considered inappropriate. [1][2] In general, collecting system constants into classes independent of behaviour, might create a poor object-oriented design, because it is often a sign of low cohesion. It is for these reasons that implementing constants interfaces is considered to be an anti-pattern.
Use of this anti-pattern has a few other downsides:
public interface Constants { public static final double PI = 3.14159; public static final double PLANCK_CONSTANT = 6.62606896e-34; } public class Calculations implements Constants { public double getReducedPlanckConstant() { return PLANCK_CONSTANT / (2 * PI); } }
Many of the pitfalls of the anti-pattern can be avoided by converting the constants interface to a proper class with no instances:
public final class Constants { private Constants() { // restrict instantiation } public static final double PI = 3.14159; public static final double PLANCK_CONSTANT = 6.62606896e-34; }
This still leaves the original intent of the pattern mostly un-addressed (i.e. there is no syntax for accessing the constants unqualified). However, since Java 5, consider using static import[2] to achieve the same goal:
import static Constants.PLANCK_CONSTANT; import static Constants.PI; public class Calculations { public double getReducedPlanckConstant() { return PLANCK_CONSTANT / (2 * PI); } }
To varying degrees, the issues listed above have now been addressed:
Note however, the changes do nothing to improve the cohesion of the Constants class, so static imports should not be considered to be a panacea.